var typeCode, typeName, typeCount;
var chartLoaded = false;
$(function () {
    init();
})

function init() {
    FastClick.attach(document.body);
    myTab("#tabBt", "#tabPage", getQueryString("index"));
    $("#elist").on("click", function () {
        window.location.href = "/elist"
    })
    reloadList(getQueryString("type"));
    $("#screen").on("change", function () {
        var screenValue = "203001,203002";
        if ($('#screen').is(':checked')) {
            screenValue = "203002";
        }
        reloadList(screenValue);
    })

    if (getQueryString("index") == 1) {
        $("#screenBox").fadeOut();
        if (!chartLoaded) {
            chartLoaded = true;
            loatChart();
        }
    }
    $(".tabButton").on("click", function (e) {
        if ($(e.target).index() == 0) {
            $("#screenBox").fadeIn();
        } else {
            $("#screenBox").fadeOut();
            if (!chartLoaded) {
                chartLoaded = true;
                loatChart();
            }
        }
    })
}

function reloadList(screenValue) {
    if (screenValue == null || screenValue == "") screenValue = "203001,203002";
    typeCode = typeName = typeCount = "";
    $("#list").html("");
    equipmemtService.queryEquipmentType({
        state: screenValue
    }, function (data) {
        if (data.success) {
            var serverData = data.datas;
            $(serverData).each(function (index, item) {
                var group = $("<div class=\"groupBox\">\n" +
                    "                    <div class=\"groupTitle\">" + item.type + "：" + item.totalNum + "台\n" +
                    "                        <div class=\"bt\"><span class=\"fa fa-plus\"> 展开</span></div>\n" +
                    "                    </div> </div>");
                $("#list").append(group);
                selectUserEquipmentBrand(group, item.code, screenValue);
                selectUserEquipmentList(group, item.code, screenValue);
            })
            bindEvent()
        } else {
            $.alert(data.errorMsg);
        }
    })
}

function selectUserEquipmentBrand(group, code, state) {
    equipmemtService.queryEquipmentBrand({code: code, state: state}, function (data) {
        if (data.success) {
            var serverData = data.datas;
            loadUInformation(serverData, group);
        } else {
            $.alert(data.errorMsg);
        }
    })
}

function selectUserEquipmentList(group, code, state) {
    equipmemtService.queryEquipmentList({oneCode: code, state: state}, function (data) {
        if (data.success) {
            var serverData = data.datas;
            loadUInformation2(serverData, group);
        } else {
            $.alert(data.errorMsg);
        }
    })
}

function loadUInformation(serverData, group) {
    var box = $("<div class=\"group\"></div>");
    group.append(box);
    $(serverData).each(function (index, item) {
        var name = item.brand.split('-');
        var row = $(' <div class="flex">\n' +
            '                            <div class="label">' + name[1] + name[2] + '</div>\n' +
            '                            <div class="value"> 累计维修' + (item.mcount == "" ? 0 : item.mcount) + '次</div>\n' +
            '                            <div class="value" style="max-width: 40px">' + item.num + '台</div>\n' +
            '                        </div>');
        box.append(row);
    })
}

function loadUInformation2(serverData, group) {
    $(serverData).each(function (index, item) {
        var name = item.name.split('-');
        var row = $(' <div class="row">\n' +
            '                        <div class="title">' + name[1] + name[2] + '</div>\n' +
            '                        <div class="subTitle">' + item.orgName + '-' + item.usePosition + '</div>\n' +
            '                        <div class="state"><span class="fa fa-tools"><br>' + baseService.getServerConstNameByCode("state", item.state) + '</span></div>\n' +
            '                        <div class="secret"><span class="fa fa-lock"><br>' + baseService.getServerConstNameByCode("secrecy", item.secrecy) + '</span></div>\n' +
            '                        <div class="flex">\n' +
            '                            <div class="label">领用日期</div>\n' +
            '                            <div class="value">2019年12月18日</div>\n' +
            '                        </div>\n' +
            '                        <div class="flex">\n' +
            '                            <div class="label">累计维修</div>\n' +
            '                            <div class="value">' + (item.mcount == "" ? 0 : item.mcount) + '次</div>\n' +
            '                        </div>\n' +
            '                        <div class="flex">\n' +
            '                            <div class="label">设备编码</div>\n' +
            '                            <div class="value">' + item.barCode + '</div>\n' +
            '                        </div>\n' +
            '                        <div class="flex">\n' +
            '                            <div class="label">二维码</div>\n' +
            '                            <div class="value">' + item.QRcodeName + '</div>\n' +
            '                        </div>\n' +
            '                    </div>');
        group.append(row);
        row.on("click", function () {
            window.location.href = "/edetail/" + item.QRcodeName;
        })
    })
}

function bindEvent() {
    $(".groupTitle").on("click", function (e) {
        var group = $(e.target);
        if (!group.hasClass("groupTitle")) {
            group = group.parents(".groupTitle");
        }
        var parent = group.parent();
        if (group.find("span").hasClass("fa-minus")) {
            parent.find(".row").slideUp();
            parent.find(".group").slideDown();
            group.find("span").html(" 展开");
            group.find("span").removeClass("fa-minus");
            group.find("span").addClass("fa-plus");
        } else {
            $(".row").slideUp();
            $(".group").slideDown();
            $(".groupTitle span").removeClass("fa-minus");
            $(".groupTitle span").addClass("fa-plus");
            $(".groupTitle span").html(" 展开");
            parent.find(".group").slideUp();
            parent.find(".row").slideDown();
            group.find("span").html(" 折叠");
            group.find("span").removeClass("fa-plus");
            group.find("span").addClass("fa-minus");
        }
    })
}

function loatChart() {
    var option = {
        color: [
            '#8bdcd5'],
        textStyle: {
            color: "#252c46"
        },
        grid: {
            left: "40px;",
            top: "50px"
        },
        xAxis: {
            axisLine: {
                lineStyle: {
                    color: '#ccc'
                }
            },
            type: 'value',
            data: []
        },
        tooltip: {
            trigger: 'axis',
            position: [150, 0]
        },
        yAxis: {
            type: 'category',
            axisLine: {
                lineStyle: {
                    color: '#ccc'
                }
            },
            axisLabel: {
                formatter: function (params, index) {
                    return index+1
                    // var arr = params.split("-");
                    // return arr[0] + " " + arr[1].substring(0, 3) + " " + params.substr(arr[0].length + arr[1].length + 2, 5);
                }
            }
        },
        series: [{
            data: [],
            name: '维修次数',
            label:{
                normal:{
                    position:[10,10],
                    show:true,
                    formatter:function(param){
                        return param.name+" 【"+param.value+"次】"
                        // var arr = params.split("-");
                        // return arr[0] + " " + arr[1].substring(0, 3) + " " + params.substr(arr[0].length + arr[1].length + 2, 5);
                    },
                    fontSize:16
                }
            },
            type: 'bar'

        }]
    };
    var dom1 = document.getElementById("chart1");
    var dom2 = document.getElementById("chart2");
    var dom3 = document.getElementById("chart3");
    var c1 = echarts.init(dom1);
    equipmemtService.analysisMaintenance({}, function (data) {
        if (data.success) {
            var serverData = data.data;
            var yAxis, series;
            //维修方式统计图开始---------
            var fs = serverData["fs"];
            yAxis = [];
            series = [];
            var countAll = 0;
            for (var i = 0; i < fs.length; i++) {
                yAxis.push(fs[i].maintenanceResult == "" ? "其他" : fs[i].maintenanceResult);
                countAll += Number(fs[i].mcount);
                series.push({
                    value: fs[i].mcount, name: (fs[i].maintenanceResult == "" ? "其他" : fs[i].maintenanceResult)
                });
            }
            var option1 = {
                textStyle: {
                    color: "#252c46"
                },
                // tooltip: {
                //     trigger: 'item',
                //     formatter: '{a} <br/>{b}: {c}次 ({d}%)'
                // },
                grid: {
                    right: "100px"
                },
                legend: {
                    orient: 'vertical',
                    left: 20,
                    top: 50,
                    textStyle: {
                        color: "#252c46"
                    },
                    data: yAxis
                },
                title: {
                    text: "维修方式统计",
                    subtext: "累计次数：" + countAll,
                    left: "20px",
                    subtextStyle: {
                        color: "#252c46",
                        fontWeight: 600
                    },
                    textStyle: {
                        color: "#252c46"
                    }
                },
                color: [
                    '#fb9f69',
                    '#c488ef',
                    '#e178b9',
                    '#e1c687',
                    '#abeb8d',
                    '#8bd8fb'],
                series: [
                    {
                        name: '维修方式',
                        type: 'pie',
                        center: ['60%', '50%'],
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            normal: {
                                show: false,
                                formatter: '{b}: {c}次 \n\n({d}%)',
                                position: 'center'
                            },
                            emphasis: {
                                show: true,
                                textStyle: {
                                    color: "#252c46",
                                    fontSize: '12'
                                }
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: series
                    }
                ]
            }

            c1.setOption(option1, true);
            //维修方式统计图 结束---------

            //型号统计 开始-------
            var xh = serverData["xh"];

            function objectAmount(a, b) {
                return b.mcount-a.mcount ;
            }

            xh.sort(objectAmount);
            yAxis = [];
            series = [];
            for (var i = 0; i < xh.length && i < 10; i++) {
                yAxis.push(xh[i].brand.substring(0, 20));
                series.push(xh[i].mcount);
            }
            option.yAxis.data = yAxis;
            option.series[0].data = series;
            option.title = {
                text: "设备型号统计",
                subtext: "不同类型、品牌、型号的维修次数",
                left: "20px",
                textStyle: {
                    color: "#252c46"
                }
            }

            $(dom2).css("height", (50 + 50 * xh.length) + "px");
            var c2 = echarts.init(dom2);
            c2.setOption(option, true);
            //型号统计 结束-------

            //设备统计 开始-------
            var zq = serverData["zq"];
            zq.sort(objectAmount);
            yAxis = [];
            series = [];
            for (var i = 0; i < zq.length && i < 10; i++) {
                yAxis.push(zq[i].usePosition.substring(0, 10) + "-" + zq[i].name.substring(0, 10));
                series.push(zq[i].mcount);
            }
            option.yAxis.data = yAxis;
            option.series[0].data = series;
            option.tooltip.position = [120, 0];
            option.color = ["#b3c3e0"];
            option.title = {
                text: "设备统计",
                subtext: "各个设备的维修情况",
                left: "20px",
                textStyle: {
                    color: "#252c46"
                }
            }
            $(dom3).css("height", (50 + 50 * zq.length) + "px");
            var c3 = echarts.init(dom3);
            c3.setOption(option, true);
            //设备统计 结束-------


        } else {
            $.alert(data.errorMsg);
        }
    })
}